import { RoomTypeEnums } from '../utils/enums'
export default function(app) {
  const { socket } = app.locals;
  const { userId, classId } = socket.handshake.query;
  // 断开连接
  socket.on('disconnect', function() {
    const { rooms, members } = app.locals;
    const { classType } = rooms[classId]
    const member = members[userId]

    if (member) {
      const options = {
        ...members[userId].json(),
        classId
      }

      // 临时房间 如果主人挂了，则解散房间
      if (classType === RoomTypeEnums.TEMPORARY) {
        socket.to(classId).emit('dissolve', options);

        if (rooms[classId] && rooms[classId].stop) {
          app.locals.rooms[classId].stop();
        }

        socket.leave(classId);
      }

      // 常驻房间 如果 主持人挂了，只通知下线。
      if (classType === RoomTypeEnums.RESIDENT) {
        socket.to(classId).emit('offline', options);
      }
    }

    if (members[userId]) {
      delete app.locals.members[userId];
    }

    if (rooms[classId]) {
      app.locals.rooms[classId].removeMember(userId as string);
    }

    // console.log('--------disconnect: members-------', members);
    // console.log('--------disconnect: rooms-------', rooms);
  });


  socket.on('disconnecting', function() {
    console.log('--------disconnecting-------')
    // socket.disconnect()
  });
  socket.on('error', function() {
    console.log('--------error-------')
  });
}



